package com.university.logistic.uitl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.InputStream;

@Component
@Data
@ConfigurationProperties(prefix =  "aliyun.oss")
public class OSSUtil {
    //节点域名
    private String host;

    //账号的身份ID
    private String accessId;

    //账号的身份凭证
    private String accessSecret;

    /**
     * 上传文件
     * @param file 文件数据
     * @param name 文件名
     * @param bucketName 存储空间名
     * @return 文件的访问地址
     */
    public String uploadFile(InputStream file, String name, String bucketName) {
        //创建客户端对象
        OSS ossClient = new OSSClientBuilder().build(
                "https://"+host, accessId,accessSecret);
        try {
            //上传
            ossClient.putObject(bucketName, name, file);
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
        return "https://" + bucketName + "."+ host + "/"+name;
    }

    /**
     * 删除文件
     * @param bucketName 存储空间名
     * @param name 文件名
     * @return
     */
    public boolean deleteFile(String bucketName,String name) {
        OSS ossClient = new OSSClientBuilder().build(
                "https://"+host, accessId,accessSecret);
        try {
            //删除文件
            ossClient.deleteObject(bucketName, name);
        } finally {
            if(ossClient != null) ossClient.shutdown();
        }
        return true;
    }



    public static boolean isPdf(byte[] header) {
        return header[0] == 0x25 && header[1] == 0x50 && header[2] == 0x44 && header[3] == 0x46;
    }

    public static boolean isGif(byte[] header) {
        return header[0] == 'G' && header[1] == 'I' && header[2] == 'F' && header[3] == '8';
    }

    public static boolean isPng(byte[] header) {
        return header[0] == (byte) 0x89 && header[1] == (byte) 0x50 && header[2] == (byte) 0x4E
                && header[3] == (byte) 0x47;
    }

    public static boolean isJpg(byte[] header) {
        return header[0] == (byte) 0xFF && header[1] == (byte) 0xD8;
    }

    public static boolean isPic(byte[] header) {
        return isJpg(header) || isGif(header) || isPng(header) || isPdf(header);
    }
}

